﻿using AutoMapper;
using MD5Hash;
using MediatR;
using SmartTracking.API.Write.Application.Commands.User;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using Yitter.IdGenerator;

namespace SmartTracking.API.Write.Application.CommandHandlers.User_handler
{
    public class AddUserCommandHandler:IRequestHandler<AddUserCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<Roles> roleRep;
        private readonly IBaseRepository<UserRoleMiddle> urRep;
        private readonly IMapper mapper;

        public AddUserCommandHandler(
            IBaseRepository<Users> userRep,
            IBaseRepository<Roles> roleRep,
            IBaseRepository<UserRoleMiddle> urRep,
            IMapper mapper)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.urRep = urRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.新增成功;
            result.Message = ApiEnum.新增成功.ToString();

            using(var tran = userRep.DB.Database.BeginTransaction())
            {
                try
                {
                    #region 添加用户
                    Users users = mapper.Map<Users>(request);
                    var count = userRep.GetAll().Where(x => x.UserName == request.UserName).Count();
                    if (count > 0)
                    {
                        throw new Exception(ApiEnum.账号已存在.ToString());
                    }
                    else
                    {
                        users.UserNo = YitIdHelper.NextId().ToString();
                        users.CreateTime = DateTime.Now;
                        users.IsDeleted = false;
                        users.Password = request.Password.GetMD5();
                        var list = await userRep.AddAsync(users);

                        #region 添加用户角色
                        List<UserRoleMiddle> userRole = new List<UserRoleMiddle>();
                        foreach (var item in request.RoleId)
                        {
                            userRole.Add(new UserRoleMiddle
                            {
                                UserId = users.UserId,
                                RoleId = item
                            });
                        }
                        await urRep.AddRangeAsync(userRole);
                        #endregion

                        tran.Commit();
                        result.data = list;
                    }
                    #endregion

                    return await Task.FromResult(result);
                }
                catch (Exception ex)
                {
                    result.Code = ApiEnum.新增失败;
                    result.Message = ApiEnum.新增失败.ToString() + ex.Message;
                    tran.Rollback();
                    throw;
                }
            }
        }
    }
}
